package com.xbongbong.paas.factory;

import com.xbongbong.paas.factory.FieldOptimizationFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.service.field.FieldOptimizationService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 字段优化处理
 * @author 吴峰
 * @date 2020/07/16 9:35
 */
public class FieldOptimizationHandle {

    public static void fieldHandle(List<FieldAttrEntity> fieldList) throws XbbException {
        Iterator<FieldAttrEntity> iterator = fieldList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = iterator.next();
            Integer fieldType = fieldAttrEntity.getFieldType();
            FieldOptimizationFactory fieldOptimizationFactory = new FieldOptimizationFactory();
            FieldOptimizationService fieldOptimizationService = fieldOptimizationFactory.getByFieldType(fieldType);
            if (StringUtil.isEmpty(fieldAttrEntity.getParentAttr())) {
                fieldAttrEntity.setParentAttr(null);
            }
            fieldOptimizationService.execute(fieldAttrEntity);
            if (ExplainUtil.isSubForm(fieldType)) {
                SubFormPoJo subFormPoJo = fieldAttrEntity.getSubForm();
                if (Objects.nonNull(subFormPoJo)) {
                    List<? extends FieldAttrEntity> subExplainList = subFormPoJo.getItems();
                    if (Objects.nonNull(subExplainList)) {
                        Iterator<? extends FieldAttrEntity> subIterator = subExplainList.iterator();
                        while (subIterator.hasNext()) {
                            FieldAttrEntity subField = subIterator.next();
                            fieldOptimizationService = fieldOptimizationFactory.getByFieldType(subField.getFieldType());
                            fieldOptimizationService.execute(subField);
                        }
                    }
                }
            }
        }
    }
}
